package com.ticket.sass.admin.business.impl;

import com.ticket.sass.admin.business.DouyinLocalLifeConfigBusiness;
import com.ticket.sass.admin.dto.input.douyin.DouyinLocalLifeConfigInput;
import com.ticket.sass.admin.dto.output.douyin.DouyinLocalLifeConfigOutput;
import com.ticket.sass.admin.service.impl.DouyinLocalLifeConfigServiceImpl;
import com.ticket.sass.common.entity.tenant.DouyinLocalLifeConfigEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author ywb
 * @date 2024-07-19 11:40
 */
@Slf4j
@Service
@AllArgsConstructor
public class DouyinLocalLifeConfigBusinessImpl implements DouyinLocalLifeConfigBusiness {
    
    @Autowired
    private DouyinLocalLifeConfigServiceImpl service;
    
    @Override
    public void saveOrUpdateConfig(DouyinLocalLifeConfigInput input) {
        Optional<DouyinLocalLifeConfigEntity> optionalEntity = Optional.ofNullable(service.getOne(null));
        
        DouyinLocalLifeConfigEntity entity;
        if (optionalEntity.isPresent()) {
            entity = optionalEntity.get();
            entity.setClientKey(input.getClientKey());
            entity.setClientSecret(input.getClientSecret());
            entity.setAccountId(input.getAccountId());
            entity.setPodId(input.getPodId());
        } else {
            entity = new DouyinLocalLifeConfigEntity();
            entity.setClientKey(input.getClientKey());
            entity.setClientSecret(input.getClientSecret());
            entity.setAccountId(input.getAccountId());
            entity.setPodId(input.getPodId());
            entity.setCreatedAt(LocalDateTime.now());
            entity.setUpdatedAt(LocalDateTime.now());
        }
        service.saveOrUpdate(entity);
    }
    
    @Override
    public Optional<DouyinLocalLifeConfigOutput> getConfigById() {
        Optional<DouyinLocalLifeConfigEntity> optionalEntity = Optional.ofNullable(service.getOne(null));
        return optionalEntity.map(this::convertToOutput);
    }
    
    private DouyinLocalLifeConfigOutput convertToOutput(DouyinLocalLifeConfigEntity entity) {
        DouyinLocalLifeConfigOutput output = new DouyinLocalLifeConfigOutput();
        output.setClientKey(entity.getClientKey());
        output.setClientSecret(entity.getClientSecret());
        output.setAccountId(entity.getAccountId());
        output.setPodId(entity.getPodId());
        return output;
    }
    
}
